package com.huarui.part.action;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.ewaf.framework.action.BaseAction;
import org.ewaf.framework.model.ListModel;
import org.ewaf.framework.util.HttpUtil;
import com.huarui.part.model.Part;
import com.huarui.part.model.PartListModel;
import com.huarui.part.model.PartProperty;
import com.huarui.part.service.PartService;
import com.huarui.partproperty.service.PartPropertyService;
import com.huarui.user.model.SessionMessage;
import com.huarui.user.security.UserHolder;
import com.huarui.util.JsonUtil;
import com.huarui.util.PinyinToolkit;
import com.opensymphony.xwork2.Action;

/**
 * xzz
 * 
 * @author Administrator
 * 
 */
public class PartPropertyAction extends BaseAction {

	private static final long serialVersionUID = 2924526709280705961L;

	private PartService partService;

	private String dir;
	private String sort;
	private Integer start;
	private Integer limit;
	private SessionMessage sessionMessage;
	private Map<String, Object> resultMap = new HashMap<String, Object>();
	private String json;
	private String queryParam;
	private PartPropertyService partPropertyService;
	public String getQueryParam() {
		return queryParam;
	}

	public void setQueryParam(String queryParam) {
		this.queryParam = queryParam;
	}

	public void setJson(String json) {
		this.json = json;
	}

	public Map<String, Object> getResultMap() {
		return resultMap;
	}

	public String getDir() {
		return dir;
	}

	public void setDir(String dir) {
		this.dir = dir;
	}

	public String getSort() {
		return sort;
	}

	public void setSort(String sort) {
		this.sort = sort;
	}



	public SessionMessage getSessionMessage() {
		return sessionMessage;
	}

	public void setSessionMessage(SessionMessage sessionMessage) {
		this.sessionMessage = sessionMessage;
	}

	public void setPartService(PartService partService) {
		this.partService = partService;
	}

	public String index() {
		sessionMessage = UserHolder.getCurrentSessionMessage();

		return "index";
	}

	public String query() throws IOException {

		HttpServletRequest request = HttpUtil.getRequest();

		sessionMessage = UserHolder.getCurrentSessionMessage();

		Integer companyId = sessionMessage.getCompanyId();

		PartListModel lm = this.getModelUtil(companyId, request);

		ListModel<PartProperty> listModel = null;

		try {
			listModel = partService.getPartPropertyByCompanyId(lm);
		} catch (Exception e) {

			resultMap.put("failure", "服务器正则升级中...");

			return "json";

		}
		
		JSONArray root = JSONArray.fromObject(listModel.getResult());
		// 分页信息
		resultMap.put("totalProperty", listModel.getTotal());
		resultMap.put("root", root);

		return "json";

	}

	public String save() throws IOException {

		sessionMessage = UserHolder.getCurrentSessionMessage();

		HttpServletRequest request = HttpUtil.getRequest();

		String jsonAll = request.getParameter("jsonAll");

		JSONObject jsonObject = JSONObject.fromObject(jsonAll);

		PartProperty partProperty = (PartProperty) JSONObject.toBean(
				jsonObject, PartProperty.class);

		Integer companyId = sessionMessage.getCompanyId();

		if (partProperty.getId() != null) {

			try {

				partService.updatePartProperty(partProperty);

			} catch (Exception e) {

				resultMap.put("failure", "更新失败");

				return "json";
			}

		} else {

			try {

				partProperty.setCompanyId(companyId);

				Part part = (Part) partService
						.getById(partProperty.getPartId());

				PartProperty p = partService
						.getPartPropertyByPartIdAndCompanyId(part.getId(),
								companyId);

				if (p != null) {

					resultMap.put("failure", "该零件属性已经存在");

					return "json";

				}

				partProperty = getPartProperty(partProperty, part);

				partProperty.setPyCode(PinyinToolkit.cn2FirstSpell(partProperty
						.getName()));

				partService.createPartProperty(partProperty);

			} catch (Exception e) {

				resultMap.put("failure", "保存失败");

				return "json";
			}
		}

		resultMap.put("success", "OK");
		return "json";
	}

	public String delete() throws IOException {

		HttpServletRequest request = HttpUtil.getRequest();

		String id = request.getParameter("id");

		if (StringUtils.isNotBlank(id)) {

			Integer partPropertyId = Integer.valueOf(id);

			try {

				PartProperty partProperty = (PartProperty) partService
						.getPartPropertyById(partPropertyId);

				partProperty.setDelete(true);

				partService.updatePartProperty(partProperty);

			} catch (Exception e) {
	
				resultMap.put("failure", "删除失败");

				return "json";

			}

		} else {

			resultMap.put("failure", "该零件属性不存在");

			return "json";
		}

		return null;
	}

	private PartProperty getPartProperty(PartProperty partProperty, Part part) {

		partProperty.setLevel1Name(part.getLevel1Name());
		partProperty.setCode(part.getCode());
		partProperty.setCost(new BigDecimal(0));
		partProperty.setOnHand(0);
		partProperty.setOnWay(0);
		partProperty.setNameEn(part.getNameEn());
		partProperty.setName(part.getName());
		partProperty.setLevel1Id(part.getLevel1Id());
		partProperty.setDurability(part.getDurability());
		partProperty.setLevel2Name(part.getLevel2Name());
		partProperty.setPartCategoryId(part.getPartCategoryId());
		partProperty.setPyCode(part.getPyCode());
		partProperty.setMeasurementUnit(part.getMeasurementUnit());

		return partProperty;

	}

	private PartListModel getModelUtil(Integer companyId,
			HttpServletRequest request) {

		PartListModel partListModel = new PartListModel();
		partListModel.setCompanyId(companyId);
		partListModel.setPageSize(limit);
		partListModel.setStart(start);
		partListModel.setOrderBy(sort);
		partListModel.setDesc(dir.equals("desc") ? true : false);

		String jsonAll = request.getParameter("jsonAll");

		if (StringUtils.isNotBlank(jsonAll)) {

			JSONObject jsonObject = JSONObject.fromObject(jsonAll);

		

			if (StringUtils.isNotBlank(jsonObject.getString("source"))) {

				Integer source = Integer
						.valueOf(jsonObject.getString("source"));

				partListModel.setSource(source);
			}
			if (StringUtils.isNotBlank(jsonObject.getString("publicanLevel"))) {

				Integer publicanLevel = Integer.valueOf(jsonObject
						.getString("publicanLevel"));

				partListModel.setPublicanLevel(publicanLevel);
			}
			
			partListModel.setCode(jsonObject.getString("code"));
            partListModel.setName(jsonObject.getString("name"));
		}

		return partListModel;
	}
	@SuppressWarnings("rawtypes")
	public String extList(){
		SessionMessage sm = UserHolder.getCurrentSessionMessage();
		ListModel listModel=new ListModel();
		listModel.setPageSize(limit == null ? 10 : limit);
		listModel.setPage(start == null ? 0 : start / limit + 1);
		listModel.setOrderBy(sort);
		if (dir != null)listModel.setDesc(dir.equals("DESC") ? true : false);
		Map<String,Object> map=new HashMap<String, Object>();
		map.put("companyId", sm.getCompanyId());
		if(json!=null){
			PartProperty partProperty=JsonUtil.getBean(json, PartProperty.class);
			map.put("publicanLevel", partProperty.getPublicanLevel());
			map.put("code_prefix", partProperty.getCode());
			map.put("name_wildcard", partProperty.getName());
			map.put("source", partProperty.getSource());
			map.put("brand_wildcard", partProperty.getBrand());
			map.put("carModel_wildcard", partProperty.getCarModel());
			map.put("origin_wildcard", partProperty.getOrigin());
			if(partProperty.getOnHand()==null){
				map.put("onHandGT0", 1);
			}
		}
		resultMap=partService.pagingByCondition(map,listModel);
		return SUCCESS;
	}
	public String savePartProperties(){
		List<PartProperty> list=JsonUtil.getList(json, PartProperty.class);
		resultMap=partService.savePartProperties(list);
		return SUCCESS;
	}
	public String savePartProperty(){
		PartProperty partProperty=JsonUtil.getBean(json, PartProperty.class);
		SessionMessage se = UserHolder.getCurrentSessionMessage();	
		partProperty.setCompanyId(se.getCompanyId());
		resultMap=partService.savePartProperty(partProperty);
		return SUCCESS;
	}
	
	@SuppressWarnings("unchecked")
	public String queryOwnerCompPartProperties() {
		SessionMessage se = UserHolder.getCurrentSessionMessage();
		Integer ownerId = se.getCompanyId();
		if( StringUtils.isNotBlank(queryParam) ) {
			JSONObject jo = JSONObject.fromObject(queryParam);
			resultMap = (Map<String, Object>) JSONObject.toBean(jo, HashMap.class);
		}
		resultMap.put("companyId", ownerId);
		
		ListModel lm = new ListModel();
		lm.setPageSize(limit == null ? 10 : limit);
		lm.setStart(start == null ? 0 : start);
		lm.setOrderBy(sort);
		
		resultMap = partService.pagingByCondition(resultMap, lm);
		
		return SUCCESS;
	}

	public String searchPartPropertyBySouAndCode(){
		PartProperty partProperty=JsonUtil.getBean(json, PartProperty.class);
		Map<String,Object> map=new HashMap<String, Object>();
		SessionMessage sm = UserHolder.getCurrentSessionMessage();
		map.put("companyId", sm.getCompanyId());
		map.put("source", partProperty.getSource());
		map.put("code", partProperty.getCode());
		map.put("partId", partProperty.getPartId());
		Map partP=partService.getPartPropertyMapByConditions(map);
		resultMap.put("partProperty", partP);
		return JSON;
	}
	public String getCodeByCompanyIdWithPage(){
		ListModel listModel=new ListModel();
		listModel.setPageSize(limit == null ? 10 : limit);
		listModel.setPage(start == null ? 0 : start / limit + 1);
		listModel.setOrderBy(sort);
		if (dir != null)listModel.setDesc(dir.equals("DESC") ? true : false);
		resultMap=partPropertyService.getCodeByCompanyIdWithPage(listModel,queryParam);
		return SUCCESS;
	}
	public Integer getStart() {
		return start;
	}

	public void setStart(Integer start) {
		this.start = start;
	}

	public Integer getLimit() {
		return limit;
	}

	public void setLimit(Integer limit) {
		this.limit = limit;
	}

	public void setPartPropertyService(PartPropertyService partPropertyService) {
		this.partPropertyService = partPropertyService;
	}

}
